var endDate=echartUtil.GetDateStr(0);
var startDate=echartUtil.GetDateStr(-10);;
var table;
var summaryTable;
var printTable;
//相关业务逻辑
$(function(){
	page.getLocalhoustUrl();
	page.bindTag();
	page.getAllSearchWhere();
	page.getCustomerName();
	page.getWarehouseInOutCreateUser();
	$("#startDay").val(startDate);
	$("#yestarday").val(endDate);
});


function dataChange(){
	startDate=$("#startDay").val();
	endDate=$("#yestarday").val();
	initTime=$("#initTime").val();
	endTime=$("#endTime").val();
}


var page={//页面总变量
		bindTag:function(){
			$("#queryWarehouseBtn").bind("click",function(){
				var object = page.getSendParam();
				if(object.warehouse===null || object.warehouse===""){
					 layer.msg("请选择仓库");
					 return false;
				}
				page.getWarehouseInOutDetail(object,"order/getWarehouseInOutDetail"); 
			});
			
			$("#warehouse").bind("change",function(){
				page.getCustomerName();
				page.getWarehouseInOutCreateUser();
			});
			 
			$("#exportExcel").bind("click",function(){
				var object = page.getSendParam();
				var sendParam = "";
				for(var i in object){
					if(object[i]!==null){
						sendParam+=i+"="+object[i]+"&"
					}
				}  
				sendParam = sendParam.substring(0,sendParam.length-1);
				var url = "companyMaterial/exportExcelFileByWarehouse?"+sendParam;
				tableUtil.download(url);
			})
			
			//当点击出入库信息时 
			$("#warehouseTable tbody").on("click","tr",function(event){
				//当点击第一单元格时,不触发查询库存事件,勾选多选
				var $target = $(event.target);
				if (!$target.is('td')){
					$target = $target.parents('td');
				}
				if($target.index()==0){
					$target.find("input").prop("checked",!$target.find("input").is(":checked"));
					//每行记录的客户名
					var customerNameLine = $(this).find("td").eq(14).text().trim();
					var customerNameVal = $("#customerName").val().trim();
					if(customerNameVal===null || customerNameVal === ''){
						 layer.msg("请先筛选客户,如果无客户可选,说明暂无出库给可的订单!");
						 $target.find("input").prop("checked",false);
						 return;
					} 
					if(customerNameVal !== customerNameLine){
						$target.find("input").prop("checked",false);
						 layer.msg("筛选的客户与需打印的客户名不一致!");
					} 
					return;
				}
				var paramVal = $(this).find("td input.materialCode").val().split(",");
				var object = new Object();
				//物料名称 
				object.materialCode=paramVal[0];
				//仓位
				var warehouse = $(this).find("td input.warehouse").val();
				if(warehouse==="原材料仓"){
					object.warehouse = 1;
				}else if(warehouse==="辅料仓"){
					object.warehouse = 2;
				}
				var url = "companyMaterial/getCompanyMaterialStackByWarehouseInOut";
				var warehouse = $(this).find("td input.warehouse").val().trim();
				if(warehouse=== "成品仓" ){
					object = new Object(); 
					object.source = $(this).find("td").eq(4).find(".source").val();
					if(object.source==="1"){ 
						object.orderId = paramVal[1];
						object.rowIndex = paramVal[2];
					} 
					object.warehouse = "3"
				}else if(warehouse=== "待处理仓" || warehouse==="报废仓"){
					if(warehouse=== "待处理仓"){
						object.warehouse = "4"
					}else{
						object.warehouse = "5"
					}
					
				}
				if(object.warehouse === undefined || object.warehouse===null){
					layAlert("错误仓位的物料信息");
					return false;
				}
				page.queryStockCount(url,object); 
			})
			$("#warehouseTable tbody").on("click","input",function(event){
				event.stopPropagation(); 
			})
			 
			$("#querySummaryBtn").bind("click",function(){
				var object = new Object();
				object.materialType=$("#materialType").val();
				object.materialName=$("#materialName").val();
				object.type=$("#type").val();
				object.queryType=$("#queryType").val();
				object.startDate = startDate; 
				object.endDate = endDate;
				//仓位
				var warehouse = $("#warehouse").val();
				if(warehouse===null || warehouse===""){
					 layer.msg("请选择仓库");
					 return false;
				}
				if(warehouse==1){//原材料
					object.warehouse = 1;
				}else if(warehouse==2){//辅料
					object.warehouse = 6;  
				}else if(warehouse==3){//成品仓
					object.warehouse = 4;
				} else if(warehouse==4){//报废仓
					object.warehouse = 2;
				}else if(warehouse==5){//待处理仓
					object.warehouse = 3;
				}
				page.getSummary(object);
			});
			
			//审批
			$('#warehouseTable tbody').on('click', '.agree', function (event) {
				event.stopPropagation();
				var object=new Object();
				object.id=$(this).attr("id");//出入库id
				object.status=1;//状态为1
				//获取制单人
				object.name = $(this).parents("tr").find("td").eq(15).text();
				var tr = $(this).parents("tr");
				var warehouse = tr.find("td input.warehouse").val();
				var source = tr.find("td input.source").val(); 
				var url = null;
				object.warehouse = warehouse;
				if(warehouse!=="成品仓" && warehouse!=="报废仓" && warehouse!=="待处理仓" && source!=="1" && source !=="2" && source !=="3"){
					object.purcharseOrderId=$(this).attr("id");//采购单号
					object.type=$(this).attr("type");//类型
					object.position = $(this).parents("tr").find("td input.Position").val().trim();
					if(object.Position ===null||object.Position===''){
						layAlert("仓位不能为空");
						return false;
					}
					url = "approval/agreeInWarehourse";
				}else{
					object.source = source;
					url = "approval/agreeOtherWarehouse";
				}
				ajaxUtil.ajaxRuquest(url,object,function(data){
					if(data==="重新确认"){
						var msg = "是否交接到车间";
						layer.confirm(msg, {
							  btn: ['是','否'] //按钮
						}, function(index){ 
							layer.close(index);
							object.isTcy = 1 //不捕获异常
							ajaxUtil.ajaxRuquest(url,object,function(data){
								layer.msg(data,{icon:1});
								table.ajax.reload( null, false);
							}); 
						}, function(index){ 
							layer.close(index);
							object.isTcy = 2 //跳过方法
							ajaxUtil.ajaxRuquest(url,object,function(data){
								layer.msg(data,{icon:1});
								table.ajax.reload( null, false);
							}); 
						});
					}else{
						layer.msg(data,{icon:1});
						table.ajax.reload( null, false);
					}
				}); 
				
			});
			//退回
			$('#warehouseTable tbody').on('click', '.return', function (event) {
				event.stopPropagation();
				var object=new Object();
				object.id=$(this).attr("id");//出入库id
				object.status=2;//状态为2
				var tr = $(this).parents("tr");
				//获取制单人
				object.name = $(this).parents("tr").find("td").eq(15).text(); 
				var warehouse = tr.find("td input.warehouse").val();
				var source = tr.find("td input.source").val(); 
				var url = null;
				object.warehouse = warehouse;
				if(warehouse!=="成品仓" && warehouse!=="报废仓" && warehouse!=="待处理仓" && source!=="1" && source!=="2" && source!=="3"){
					object.purcharseOrderId=$(this).attr("id");//采购单号
					object.type=$(this).attr("type");//类型
					url = "approval/agreeInWarehourse";
				}else{
					object.source = source;
					url = "approval/agreeOtherWarehouse";
				}
				$("#reportReasonModel").modal("show");
				$("#reportReturnBtn").show();
				$("#reportReturnBtn").unbind("click");
				$("#reportReturnBtn").bind("click", function () {
					var approvalReason = $("#reportReturnReason").val();
					if (approvalReason == "") {
						approvalReason = "退回"; 
					} 
					object.approvalReason = approvalReason;
					ajaxUtil.ajaxRuquest(url,object,function(data){
						$("#reportReasonModel").modal("hide");
						layer.msg(data,{icon:1});
						table.ajax.reload( null, false);
					});   
					 
				});

				
			});
			//修改
			$('#warehouseTable tbody').on('click', '.update', function (event) {
				event.stopPropagation();
				var object=new Object();
				object.id=$(this).attr("id");//出入库id
				object.purcharseOrderId=$(this).attr("id");//采购单号
				object.type=$(this).attr("type");//类型
				object.status=0;//状态为1
				var tr = $(this).parents("tr");
				var source = tr.find("td input.source").val(); 
				var url = "approval/updateWarehouseInOut";
				if(object.type==7 || source==="1"){
					layAlert("请至我的报工页面修改");
					return false;
				} 
				if(source==="1"){//假如前台拦截出了问题. 那么就继续后台拦截
					url = "approval/updateOtherWarehouse";			
				}
				if(source==="2" || source==="3"){
					object.source = source;
					url = "approval/updateOtherWarehouseByOrder";		
				}
				layer.prompt({title: '请输入修改数量', formType: 2}, function(text, index){
					if (!/^(0|[1-9]\d*)(\.\d{1,4})?$/.test(text)) {
						layAlert("入库数量小数点后必须是1-4位"); 
						return false; 
					} 
					object.count=text;
					ajaxUtil.ajaxRuquest(url,object,function(data){
						layer.msg(data,{icon:1});
						table.ajax.reload( null, false);
					});
				});
			});
			//删除
			$('#warehouseTable tbody').on('click', '.delete', function (event) {
				event.stopPropagation();
				var object=new Object();
				object.id=$(this).attr("id");//出入库id
				object.purcharseOrderId=$(this).attr("id");//采购单号
				object.type=$(this).attr("type");//类型
				var tr = $(this).parents("tr");
				var warehouse = tr.find("td input.warehouse").val();
				var source = tr.find("td input.source").val();
				object.source = source;
				object.warehouse = warehouse;
				if(object.type==7 || object.source==="1"){ 
					var msg = "此记录为车间交接至仓库，删除将同时删除车间报工数据";
					if(source==="1"){
						msg = "此记录为车间交接至"+warehouse+"，删除将同时删除车间报工数据";
					}
					layer.msg(msg, {
						  time: 0 //不自动关闭
						  ,btn: ['确定', '取消']
						  ,yes: function(index){
						    layer.close(index);
						    var url = "approval/deleteWarehouseInOut";
						    if(source==="1"){
						    	url = "approval/deleteOtherWarehouse";
						    }
						    ajaxUtil.ajaxRuquest(url,object,function(data){
								layer.msg(data,{icon:1});
								table.ajax.reload( null, false);
							});  
						  }
						});
				}else{
					if(object.source==="2" || object.source=="3"){
						var requestUrl = "approval/deleteOtherWarehouse";
					}else{
						var requestUrl = "approval/deleteWarehouseInOut";
					}
					ajaxUtil.ajaxRuquest(requestUrl,object,function(data){
						layer.msg(data,{icon:1});
						table.ajax.reload( null, false);
					});
				}
			});
			
			//点击打印时调用
			$("#printWarehouse").on("click",function(){
				page.printWarehouse();
			})
		}, 
		pageSearchWhereArray:[],//物料筛选条件数组（物料信息）
		pageIdArray:['providerName','materialName','model','color'],
		pageFinishWhereArray:[],//成品筛选条件数组（订单信息）
		pageFinishIdArray:['factoryId','coustomId','orderId'],
		getAllSearchWhere:function(){/**获取所有筛选条件*/
			ajaxUtil.ajaxRuquestNoQuan('companyMaterial/getAllSearchWhere',null,function(data){
				page.pageSearchWhereArray=data.materialSet;
				page.pageFinishWhereArray=data.orderSet;
				filterInput.filterView("",page.pageIdArray,page.pageSearchWhereArray);
				filterInput.filterView("",page.pageFinishIdArray,page.pageFinishWhereArray);
			}); 
		},
		getSendParam:function(){
			/**
			 * 配置要素绑定
			 */
			for(var i=0;i<page.pageIdArray.length;i++){
				$("#"+page.pageIdArray[i]).bind("change",function(){
					filterInput.filterView("",page.pageIdArray,page.pageSearchWhereArray);
				});
			}
			for(var i=0;i<page.pageFinishIdArray.length;i++){
				$("#"+page.pageFinishIdArray[i]).bind("change",function(){
					filterInput.filterView("",page.pageFinishIdArray,page.pageFinishWhereArray);
				});
			}
			var object = new Object();
			var modelVal = model=$("#model").val().trim();
			if(modelVal!==""){
				object.model=modelVal;
			} 
			object.providerName=$("#providerName").val().trim();
			var colorVal = $("#color").val().trim();
			if(colorVal!==""){
				object.color = colorVal;
			} 
			var createUser = $(".createUserList").filterSelect("getValue","id");
			if(createUser!==''){
				object.createUser = createUser;
			}
			object.materialName=$("#materialName").val().trim();
			object.customerName = $("#customerName").val().trim();
			object.type=$("#type").val();
			object.queryType=$("#queryType").val();
			object.orderId = $("#orderId").val();
			object.factoryNo = $("#factoryId").val();
			object.customerNo = $("#coustomId").val();
			object.startDate = $("#startDay").val();
			object.endDate = $("#yestarday").val();
			object.status = $("#status").val();
			object.warehouse = $("#warehouse").val();
			return object;
		},
		checkboxPrint:function(el){
			var $tr = $(el).parents("tr"); 
			var customerNameLine = $tr.find("td").eq(14).text().trim();
			var customerNameVal = $("#customerName").val().trim();
			if(customerNameVal===null || customerNameVal === ''){
				 $(el).prop("checked",false);
				 layer.msg("请先筛选客户,如果无客户可选,说明暂无出库给可的订单!");
				 return;
			} 
			if(customerNameVal !== customerNameLine){
				$(el).prop("checked",false);
				 layer.msg("筛选的客户与需打印的客户名不一致!");
			} 
		},
		getWarehouseInOutDetail:function(object,url){
			$("#allOrder").show();
			$("#printDiv").hide();
			$("#sumDiv").hide(); 
			table=ajaxUtil.dataTablesAjaxNotFxiaction("warehouseTable",8,url,
					object,[ 
					{"data":"type",render:function(data,type,row){ 
						return "<input type = 'checkbox' id='"+row.id+"' onclick='page.checkboxPrint(this)' />";
					}}, 
					{"data":"type",render:function(data,type,row){
						if(data==2 || data==5|| data==9){
							return "出库"; 
						}
						if(data==1 || data==3 || data==4 || data==7 || data==8){
							return "入库";
						}
					}}, 
					{"data":"status",render:function(data,type,row){
						if(data==0){
							return "未确认";
						}
						if(data==1){
							return "已确认";
						}
						if(data==2){
							return "退回";
						}
					}},
					{"data":"type",render:function(data,type,row){
	                       var html="";
							//公司配置仓库本人是否可以审核自己的
	                        if(row.isApperval===1){
								//未审核
								if(row.status==0){ 
									if(row.isCreate==1){
									   html+="<div style='width:240px;'>" +
									   		"<button class='btn btn-primary radius update' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>修改</button>"+
									   		"<button class='btn btn-primary radius delete' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>删除</button>"+
									   		"<button class='btn btn-primary radius agree' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>确认</button>"+
									   		"<button class='btn btn-primary radius return' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>退回</button>" +
									   		"</div>";
									}else{
										 html+="<div style='width:240px;'>" +
									   		"<button class='btn btn-primary radius agree' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>确认</button>"+
									   		"<button class='btn btn-primary radius return' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>退回</button>" +
									   		"</div>";
									}
								}  
	                       }else{ 
	                    	   if(row.status==0 && row.isCreate==1){
								   html+="<div style='width:240px;'>" +
								   		"<button class='btn btn-primary radius update' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>修改</button>"+
								   		"<button class='btn btn-primary radius delete' purcharseOrderId='"+row.purcharseOrderId+"' id='"+row.id+"' type='"+data+"'>删除</button>"+
								   		"</div>";
								}
	                       }
							return html;
					}},
					{"data":"count",render:function(data,type,row){ 
						return "<td><input type='hidden' class = 'warehouse' value='"+row.warehouse+"'/><input type='hidden' class = 'source' value='"+row.source+"'/>"+data+"</td>";
					}}, 
					{"data":"materialName",render:function(data,type,row){
						return "<td><input type='hidden' class='materialCode' value='"+row.materialCode+","+row.orderId+","+row.rowIndex+","+row.providerName+"'/>"+data+"</td>";
					}},
					{"data":"model"}, 
					{"data":"color"},
					{"data":"providerName"},
					{"data":"colorDescription"},
					{"data":"companyOrderId"},
					{"data":"factoryNo"},
					{"data":"customerNo"},
					{"data":"remark"},
					{"data":"customerName",render:function(data,type,row){
						return (data===null?"":data);
					}},  
					{"data":"createUser"},
					{"data":"createTime"},
					{"data":"approvalUser"},
					{"data":"approvalTime"},
					{"data":"position",render:function(data,type,row){
						if(row.status==0){
								return "<td><input style='width:80px' class='input-text Position' type='text' value = '"+(data==null?"":data)+"'/></td>";
						}else{
							return data;
						}
					}}
					
			],[0],function(td, cellData, rowData, row, col){
						if(rowData.type==2 || rowData.type==5){
							$(td).parent().addClass("twoTwo"); 
						}
				    });
		},
		//获取出入库中的客户名称 
		getCustomerName:function(){
			var warehouse = $("#warehouse").val();
			console.log("warehouse",warehouse);
			ajaxUtil.ajaxRuquest("basicData/getCustomerNameByWarehouse",{warehouse:warehouse},function(data){
				var customerNameList = $("#customerNameList");
				if(data!=null && data.length>0){					
					var option = "";
					for(var i = 0;i<data.length;i++){
						option+=" <option value='"+data[i]+"'>"+data[i]+"</option>   ";
					}
					customerNameList.html(option);
				}else{
					customerNameList.html("");
				}
			});
		},
		//获取出入库制单人
		getWarehouseInOutCreateUser:function(){
			//仓库
			var warehouse = $("#warehouse").val();
			ajaxUtil.ajaxRuquest("basicData/getWarehouseInOutCreateUser",{warehouse:warehouse},function(data){
				if(data !=null && data.length>0){
					var head = {"id":'',"userName":"请选择"};
					data.unshift(head);
					var option = {
							data:_.map(data,function(d){
								return {
									id:d.id,
									name:d.userName
								} 
							}),
							valueField:"id", 
							labelField:"name" 
					}  
					$(".createUserList").filterSelect("destroy");
					$(".createUserList").filterSelect(option);
				}
			});
		},
		getSummary:function(object){
			$("#allOrder").hide();
			$("#printDiv").hide();
			$("#sumDiv").show();
			summaryTable=ajaxUtil.dataTablesAjax("summaryTable",10,"order/getinOutSummary",
					object,[
					{"data":"materialName"},
					{"data":"model"},
					{"data":"color"},
					{"data":"providerName"},
					{"data":"inCount"},
					{"data":"outCount"},
					{"data":"startCount"},
					{"data":"endCount"}
					
			]);
		},
		queryStockCount:function(url,object){
			$("#queryStockCountModel").modal("show");
			ajaxUtil.ajaxRuquest(url,object,function(data){ 
				var tbody = $("#queryStockTable tbody");
				var html ="";
				if(data!==null&&data.length>0){
					for(var i = 0;i<data.length;i++){
						html+="<tr>" +
									"<td>"+(data[i].materialName===null?'':data[i].materialName)+"</td>" +
									"<td>"+(data[i].model===null?'':data[i].model)+"</td>"+
									"<td>"+(data[i].color===null?'':data[i].color)+"</td>"+
									"<td>"+(data[i].providerName===null?'':data[i].providerName)+"</td>"+
									"<td>"+data[i].defaultWarehouse+"</td>"+
									"<td>"+(data[i].count+" "+(data[i].unit===null?"":data[i].unit))+"</td>"+
									"<td>"+(data[i].productionUnitCount!==null?(data[i].productionUnitCount+" 付"):"")+"</td>"+
								"</tr>";  
					} 
				}else{ 
					html+="<tr><td colspan='7'>暂无库存信息</td></tr>";
				}
				tbody.html(html);
				
			});
		},
		//获取出入库需打印信息
		getWarehouseInOutDetailPrint:function(object){
			ajaxUtil.ajaxRuquest("companyMaterial/getWarehouseInOutDetailByPrint",object,function(data){
				var html = ""; 
				if(data !=null && data.length>0){
					for(var i=0;i<data.length;i++){  
						html+="<tr>" + 
								"<td>"+(data[i].materialName==null?"":data[i].materialName)+"</td>"+
								"<td>"+(data[i].model==null?"":data[i].model)+"</td>"+
								"<td>"+(data[i].color==null?"":data[i].color)+"</td>"+
								"<td>"+(data[i].colorDescription==null?"":data[i].colorDescription)+"</td>"+
								"<td>"+(data[i].factoryNo==null?"":data[i].factoryNo)+"</td>"+
								"<td>"+(data[i].customerNo==null?"":data[i].customerNo)+"</td>"+
								"<td>"+(data[i].count==null?0:data[i].count)+"</td>"+
								"<td>"+(data[i].inOutUnit==null?"无":data[i].inOutUnit)+"</td>"+
								"<td>"+(data[i].inCountPrice==null?0:data[i].inCountPrice).toFixed(2)+"</td>"+
								"<td>"+(data[i].count*data[i].inCountPrice).toFixed(2)+"</td>"+
								"<td>"+(data[i].remark==null?"":data[i].remark)+"</td>"+ 
							  "</tr>"; 
					}
					//发货人
					var loginUser = window.sessionStorage.getItem("user");
					if(loginUser!==undefined){
						var user = JSON.parse(loginUser);
						$("#consigner").html(user.userName); 
					}
					//收货客户
					var receiveCustomer = $("#customerName").val();
					$("#receiveCustomer").html(receiveCustomer);
					//送货时间 
					var deliveryTime = moment().format("YYYY-MM-DD HH:mm:ss");
					$("#createTime").html(deliveryTime); 
					$("#warehouseTablePrint tbody").html(html); 
					//调用客户信息.进行打印
					window.print(); 
				} 
			});
		},
		//打印记录
		printWarehouse:function(){
			//需要打印的物料数组
			var warehouseArray = [];
			$("#warehouseTable tbody tr").each(function(){
				var checked = $(this).find("td").eq(0).find("input").is(":checked");
				if(checked){ 
					var id = $(this).find("input").attr("id")	
					warehouseArray.push(id);
				}
			}); 
			var ids = warehouseArray.join(",");
			var object = {
					"ids":ids
			}; 
			if(object.ids===null || object.ids===""){
				layAlert("未勾选需要打印的出入库记录");
				return false;
			}
			page.getWarehouseInOutDetailPrint(object);
		},
		//获取参数
		getLocalhoustUrl:function(){
			var urlData = requestUtil.getRequest();
			var object = new Object();
			console.log("urlData",urlData);
			if(urlData !==null && urlData['ids'] !== undefined && urlData['ids'] !==''){ 
				object.ids = urlData['ids']; 
				this.getWarehouseInOutDetail(object,"order/getWarehouseInOutDetailByIds");
			}
		}
}
